package com.zlyx.easy.drools.validate;

import com.zlyx.easy.drools.builder.RuleBuilder;
import com.zlyx.easy.drools.domain.RuleContextDomain;
import com.zlyx.easy.drools.executor.RuleExecutor;
import com.zlyx.easy.drools.util.RuleUtils;

/**
 * 规则验证&JAVA导出规则
 * 
 * @Author 赵光
 * @Desc DroolsTest
 * @Date 2020年5月11日
 */
public class RuleValidator extends RuleReader {

	/**
	 * 验证规则
	 *
	 * @param executor 规则执行器
	 * @return
	 * @throws Exception
	 */
	public static <T> String validate(RuleExecutor<T> executor) throws Exception {
		return validate(DEFAULT_RULE_NAME, executor);
	}

	/**
	 * 验证规则
	 *
	 * @param ruleName 规则名称
	 * @param executor 规则执行器
	 * @return
	 * @throws Exception
	 */
	public static <T> String validate(String ruleName, RuleExecutor<T> executor) throws Exception {
		return validate(ruleName, DEFAULT_RULE_PATH, executor);
	}

	/**
	 * 验证规则
	 *
	 * @param ruleName 规则名称
	 * @param rulePath 规则路径
	 * @param executor 规则执行器
	 * @return
	 * @throws Exception
	 */
	public static <T> String validate(String ruleName, String rulePath, RuleExecutor<T> executor) throws Exception {
		RuleBuilder.RuleBody ruleBody = RuleUtils.readRule(rulePath);
		return validate(ruleBody.name(ruleName), executor);
	}

	/**
	 * 验证规则
	 *
	 * @param ruleBody 规则
	 * @param executor 规则执行器
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static <T> String validate(RuleBuilder.RuleBody ruleBody, RuleExecutor<T> executor) throws Exception {
		if (executor == null) {
			executor = (RuleExecutor<T>) new RuleExecutor<RuleContextDomain>() {
				@Override
				public RuleContextDomain initContext() throws Exception {
					return new RuleContextDomain();
				}
			};
		}
		return executor.validate(ruleBody.name(), ruleBody, null);
	}
}
